<template>
  <div class="login">
      <div class="container">
      <img src="@/assets/1.gif" class="avatar" alt="">
    <el-form
      :model="loginForm"
      :rules="rules"
      ref="loginform"
      class="demo-ruleForm"
    >
      <el-form-item prop="username">
        <el-input clearable placeholder="请输入用户名" v-model="loginForm.username" prefix-icon='el-icon-user-solid
'></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input clearable placeholder="请输入密码" v-model="loginForm.password" prefix-icon='el-icon-key' show-password></el-input>
      </el-form-item>
      <el-form-item>
      <el-button type="primary" class="login-btn" @click='loginsubmit' round>登录</el-button>
      </el-form-item>
    </el-form>

  </div>
  </div>
</template>

<script>
import { login } from '@/api/user_api.js'
export default {
  data () {
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 18,
            message: '密码长度在 6 到 18 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    loginsubmit () {
      this.$refs.loginform.validate(valid => {
        if (valid) {
          // console.log(login(), 'login')
          login(this.loginForm)
            .then(res => {
              console.log(res, 'login')
              // 如果返回登录成功
              if (res.data.meta.status === 200) {
                // 就把token数据存入本地
                localStorage.setItem('user_token', res.data.data.token)
                this.$message.success(res.data.meta.msg)
                // 并跳转路由
                this.$router.push({ name: 'index' })
              } else {
                this.$message.error(res.data.meta.msg)
              }
            })
            .catch(err => {
              this.$message.error(err)
            })
        } else {
          this.$message.error('输入错误，请检查用户名和密码')
          return false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login {
  position: fixed;
  width: 100%;
  height: 100%;
  background-color: #2f4050;
  .container {
    position: absolute;
    left: 0;
    right: 0;
    width: 400px;
    padding: 0px 40px 15px 40px;
    margin: 200px auto;
    background: white;
    .avatar {
      position: relative;
      left: 50%;
      width: 120px;
      height: 120px;
      margin-left: -60px;
      margin-top: -60px;
      box-sizing: border-box;
      border-radius: 50%;
      border: 10px solid #fff;
      box-shadow: 0 1px 5px #ccc;
      overflow: hidden;
    }
    .login-btn {
      width: 100%;
    }
  }
}
</style>
